package labox.innovation.gameserver.network.clientpackets;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map.Entry;
import labox.innovation.config.Config;
import labox.innovation.gameserver.ThreadPoolManager;
import labox.innovation.gameserver.model.actor.instance.FuzePcInstance;
import labox.innovation.gameserver.network.serverpackets.GUIList;
import labox.innovation.pay.DepositConfig;
import labox.innovation.pay.PayCard;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author lian 请求充值
 */
public class RequestDeposit extends L2GameClientPacket {

	private static Logger _log = LoggerFactory.getLogger(RequestDeposit.class);

	private static final String C_REQUESTDEPOSIT = "C_RequestDeposit";
	private static final String RECHARGEGUI = "<form nm='exit' w='210' h='170' tl='充值系统'> " + 
											"@@ <br/>" + 
											"如果您有问题或者连续充值失败请咨询乾坤客服：021-32504360,我们尽快帮您解决," +
											"感谢您对乾坤的支持。" + "</form>";
	/**
	 * 卡的类型
	 */
	private int cardType;
	/**
	 * 卡号
	 */
	private String cardNo;
	/**
	 * 卡密
	 */
	private String cardPassword;
	/**
	 * 金额
	 */
	private int money;
	/**
	 * 渠道ID
	 */
	private String unionId;

	@Override
	public String getType() {
		return C_REQUESTDEPOSIT;
	}

	@Override
	protected void readImpl() {
		cardType = readByte();
		cardNo = readString();
		cardPassword = readString();
		money = readShort();

	}

	@Override
	protected void runImpl() {
		FuzePcInstance active = getClient().getActiveChar();
		unionId = getClient().getChannelId();
		if (active == null || unionId == null) {
			return;
		}
		ThreadPoolManager.getInstance().execute(new DepositHttpClient(active, cardType, cardNo, cardPassword, money, unionId));
	}

	/**
	 * 使用GET方式提交数据 为”SZX”: 神州行卡支付 为”SNDACARD”: 盛大卡支付 为”ZHENGTU”: 征途卡支付
	 * 为”JUNNET”:骏网一卡通支付 为”QQCARD”: Q币支付 为”YPCARD”: 易宝一卡通卡支付 为” UNICOM”: 联通卡支付
	 * 充值方式ID枚举：0神州行充值卡（推荐），1骏网一卡通，2征途卡，3盛大卡，4 Q币卡，5 联通卡
	 * 
	 * @return
	 * @throws SQLException
	 */
	private static class DepositHttpClient implements Runnable {
		private FuzePcInstance player;
		private int cardType;
		private String cardNo;
		private String cardPassword;
		private int money;
		private String unionId;

		public DepositHttpClient(FuzePcInstance player, int cardType, String cardNo, String cardPassword, int money, String unionId) {
			super();
			this.player = player;
			this.cardType = cardType;
			this.cardNo = cardNo;
			this.cardPassword = cardPassword;
			this.money = money;
			this.unionId = unionId;
		}

		@Override
		public void run() {
			URL url = null;
			String recharge = null;// 充值名称
			HttpURLConnection httpConnection = null;
			try {
				StringBuilder link = new StringBuilder();
				link.append(DepositConfig.REQUEST_URL); // 充值平台URL
				link.append("?");
				link.append("qudao_id="); // 渠道ID
				link.append(unionId);
				link.append("&pa7_cardAmt=");// 充值金额
				link.append(money);
				link.append("&p3_Amt=");// 充值金额
				link.append(money);
				link.append("&pa8_cardNo=");// 充值卡号
				link.append(cardNo);
				link.append("&pa9_cardPwd=");// 充值密码
				link.append(cardPassword);
				link.append("&pd_FrpId=");
				for (Entry<String, PayCard> entry : DepositConfig.getALLPAYCARDS().entrySet()) {
					PayCard payCard = entry.getValue();
					if (payCard.getPayId() == cardType) {// 如果匹配
						link.append(payCard.getType());// 充值卡号类型
						recharge = payCard.getName();// 卡号类型名字
					}
				}
				link.append("&remark=");
				link.append(player.getAccountName());// 角色名
				link.append("-");
				link.append(player.getObjectId());// 角色ID
				link.append("-");
				link.append("innovation" + Config.SERVER_ID);// 角色服务器ID
				_log.info("充值请求:" + link.toString(), player.getObjectId(), player.getName());
				url = new URL(link.toString());
				httpConnection = (HttpURLConnection) url.openConnection();
				// 设置连接主机超时(单位:毫秒)
				httpConnection.setConnectTimeout(5000);
				// 设置从主机读取数据超时(单位:毫秒)
				httpConnection.setReadTimeout(10000);
				httpConnection.setRequestMethod("GET"); // GET方式提交数据
				int responseCode = httpConnection.getResponseCode();
				if (responseCode == HttpURLConnection.HTTP_OK) {

					player.sendPacket(new GUIList(RECHARGEGUI.replace("@@", "您的充值消息发送成功 请稍候...")));
//					player.sendMessage("充值发送成功,验证中");
					_log.info("充值发送成功:角色ID= " + player.getObjectId() + " 账号=" + player.getAccountName() + " 角色名= " + player.getName() + " 充值类型=" + recharge + " 充值卡号=" + cardNo + " 渠道ID=" + unionId + "", player.getObjectId(), player.getName());

				} else {

					player.sendPacket(new GUIList(RECHARGEGUI.replace("@@", "充值系统维护中,您的充值消息发送失败 ,请稍候再充值...")));
//					player.sendMessage("充值发送失败");
					_log.error("充值发送失败 :Http请求没有返回充值状态 账号=" + player.getAccountName() + " 角色名= " + player.getName() + " 充值类型=" + recharge + " 充值卡号=" + cardNo + " 渠道ID=" + unionId + "", player.getObjectId(), player.getName());

				}
			} catch (Exception e) {
				player.sendPacket(new GUIList(RECHARGEGUI.replace("@@", "充值系统网络出现异常,您的充值消息发送失败 ,请稍候再充值...")));
//				player.sendMessage("充值发送失败");
				_log.error("充值发送失败:账号=" + player.getAccountName() + " 角色名= " + player.getName() + " 充值类型=" + recharge + " 充值卡号=" + cardNo + " 渠道ID=" + unionId + " 服务器ID=" + Config.SERVER_ID + "", player.getObjectId(), e);
			} finally {
				try {
					if (httpConnection != null)
						httpConnection.disconnect();
				} catch (Exception e) {
					_log.error("充值发送失败:关闭异常", Config.SERVER_ID, e);
				}
			}

		}
	}

}
